﻿using ISolutions.xRM.TechDays.ContactCard.Utilities;
using ISolutions.xRM.TechDays.Shared;
using Microsoft.Xrm.Sdk.Client;
using System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace ISolutions.xRM.TechDays.ContactCard
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            usernameBox.Text = StaticSettings.Username;
            passwordBox.Password = StaticSettings.Password;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var creds = new AuthenticationCredentials();
            creds.ClientCredentials.UserName.UserName = usernameBox.Text;
            creds.ClientCredentials.UserName.Password = passwordBox.Password;

            CrmConnectionManager.Connected += CrmConnector_Connected;
            CrmConnectionManager.Connect(creds);
        }

        private async void CrmConnector_Connected()
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.Frame.Navigate(typeof(CreateContact)));
        }
    }
}
